from django.db import models
from apps.system.models import Upload
from apps.project_case.models import House
from apps.member.models import Member

from utils.exceptions import CustomError


class Circle(models.Model):
    content = models.CharField(max_length=100, verbose_name='内容')
    member = models.ForeignKey(Member, verbose_name='用户', on_delete=models.PROTECT)
    images = models.ManyToManyField(Upload, verbose_name='图片')
    like_count = models.IntegerField(verbose_name='点赞数', default=0)
    brown_count = models.IntegerField(verbose_name='浏览数', default=0)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    house = models.ForeignKey(House, verbose_name='案例', on_delete=models.PROTECT, null=True)

    class Meta:
        db_table = 'circle'
        default_permissions = ()
        ordering = ['-create_time']
        verbose_name = '圈子'

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的id')

        instance = Circle.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的实例')
        return instance


class CircleComment(models.Model):
    member = models.ForeignKey(Member, verbose_name='评论人', on_delete=models.PROTECT)
    circle = models.ForeignKey(Circle, verbose_name='圈子', on_delete=models.PROTECT)
    content = models.CharField(verbose_name='内容', max_length=200)
    like_count = models.IntegerField(verbose_name='点赞数', default=0)
    delete = models.BooleanField(verbose_name='删除', default=False, editable=False)
    create_time = models.DateTimeField(verbose_name='评论时间', auto_now_add=True)

    class Meta:
        db_table = 'circle_comment'
        default_permissions = ()
        verbose_name = '圈子_评论'
        ordering = ('-like_count', 'create_time')

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的id')

        instance = CircleComment.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的实例')
        return instance
